<?php
/**
 *
 *
 *
 */
class Yz_Form_Element_Date
    extends Yz_Form_Element_Input
{

    public function render(Yz_Template_Interface $template)
    {
        debug();
        $date = new Yz_Date($this->value);
        $elemId = 'yz-form-element-' . $this->name;
        $this->includeJS($template, $date, $elemId);
        $o = <<<html
            <input type="text" name="{$this->name}" id="{$elemId}" value="{$date}" size="10" />\n
html;
        return $o;
    }

    /** validate input: ensure that input is a valid date
     *
     */
    protected function validateType($input)
    {
        $val = parent::validate($input); // {null|string}
        if ($val) {
            try {
                $val = new Yz_Date($val);
            } catch (ValueError $ex) { // other error type => system fault
                throw Yz_Form_Element_Error_ValueError::_new_();
            }
        }
        return $val;
    }


    protected function includeJS($template, $date, $elemId)
    {
        if ($date->isEmpty()) {
            $date = Yz_Date::fromTimestamp(YZ_TIME);
        }
        $y = $date->getYear();
        $m = $date->getMonth();
        $d = $date->getDay();
        $webRoot = $template->webRoot;
        // TODO choose correct language
        $lang = 'ru';
        $js = <<<js
    Yz.jqueryui(function(){
        Yz.fetchScript('{$webRoot}www/jquery/datepicker-i18n/{$lang}.js');
        $( function() {
            $("#{$elemId}").datepicker( {
                defaultDate: new Date({$y}, {$m}-1, {$d}), // NOTE: months start from 0
                changeYear: true
            });
        });
    });
js;

        $template->includeJS('datepicker', $js);
        return $this;
    }

}
